<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>权限管理</title>
    <link rel="stylesheet" href='/plug-in/pear/css/pear.css' media="all">
    <link rel="stylesheet" href='/css/base.css'>
    <style>
        .layui-btn-container .layui-btn {margin-bottom: 0;}
        .add-menu-form{display: none;padding: 45px;}
        .layui-iconpicker-icon{background-color: transparent !important;}
        .menu-box xm-select{border: 0;}
        .menu-box .xm-label.auto-row{display: none;}
    </style>
</head>
<body>
<div class="page-content" shiro:hasPermission="system.authority.list">
    <table id="menuTreeTb"></table>
</div>
<div class="add-menu-form">
    <form class="layui-form" action="" lay-filter="form-obj" style="width: 500px; margin: 0 auto;">
        <div class="layui-form-item" id="parent-menu">
            <label class="layui-form-label towexin-form-label">上级节点：</label>
            <div class="layui-input-block">
                <div id="setAuthority" style="margin-right: 2px;" class="xm-select-demo"></div>
            </div>
        </div>
        <div class="layui-form-item m-name layui-hide">
            <div class="layui-input-block">
                <input type="text" name="pid" class="layui-input">
                <input type="text" name="id" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item m-name">
            <label class="layui-form-label towexin-form-label layui-required" id="showName">权限名称：</label>
            <div class="layui-input-block">
                <input type="text" name="authorityName" lay-verify="required" autocomplete="off" placeholder="请输入名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item m-href">
            <label class="layui-form-label towexin-form-label layui-required">权限标识：</label>
            <div class="layui-input-block">
                <input type="text" name="authorityMark" lay-verify="required" placeholder="请输入权限标识" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label towexin-form-label">排序：</label>
            <div class="layui-input-block">
                <input type="number" name="sort" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label towexin-form-label">按钮：</label>
            <div class="layui-input-block">
                <input type="checkbox" name="btn" lay-skin="switch" lay-filter="switchIsBtn" lay-text="是|否">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: right;">
                <button type="submit" id="submit-type" class="pear-btn pear-btn-primary" lay-submit="" lay-filter="add">立即提交</button>
            </div>
        </div>
    </form>
</div>

<div class="menu-box" style="display: none; padding: 20px">
    <div id="setTree" style="margin-right: 2px;" class="xm-select-demo"></div>
</div>

<script type="text/html" id="toolbarTop">
    <div class="layui-btn-container">
        <button shiro:hasPermission="system.authority.list" class="layui-btn layui-btn-sm layui-bg-black" lay-event="refresh"><span class="fa fa-refresh" title="刷新表格" aria-hidden="true"></span></button>
        <button shiro:hasPermission="system.authority.add" class="layui-btn layui-btn-sm layui-bg-blue" lay-event="newModel"><span class="fa fa-plus-circle" aria-hidden="true"></span> 添加</button>
    </div>
</script>
<!-- 操作列 -->
<script type="text/html" id="auth-state">
    <button shiro:hasPermission="system.authority.edit" class="layui-btn layui-btn-success layui-btn-xs" lay-event="edit">编辑</button>
    <button shiro:hasPermission="system.authority.delete" class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</button>
    {{#  if(d.btn==false){ }}
    <button shiro:hasPermission="system.authority.add" class="layui-btn layui-btn-normal layui-btn-xs" lay-event="add">添加下级</button>
    <button shiro:hasPermission="system.authority.associate" class="layui-btn layui-btn-warm layui-btn-xs" lay-event="associate">关联菜单</button>
    {{#  } }}
</script>
<script src="/plug-in/jquery/jquery-3.5.1.min.js" charset="utf-8"></script>
<script src='/plug-in/layui/layui.js' charset="utf-8"></script>
<script src='/plug-in/lay-config.js' charset="utf-8"></script>
<script type="text/javascript" th:inline="none" shiro:hasPermission="system.authority.list">
    layui.use(["treeTable", "xmSelect"], function(){
        let form = layui.form, layer=layui.layer, treeTable = layui.treeTable, element=layui.element, xmSelect=layui.xmSelect;
        let flag = true
        // 渲染树形表格
        var treeTb = treeTable.render({
            elem: '#menuTreeTb',
            toolbar: "#toolbarTop",
            defaultToolbar: false,
            skin: "line",
            tree: {
                iconIndex: 0,           // 折叠图标显示在第几列
                isPidData: true,        // 是否是id、pid形式数据
                idName: 'id',  // id字段名称
                pidName: 'pid',     // pid字段名称
            },
            cols: [[
                {field: 'authority_name', title: '我的权限', minWidth: 120},
                {field: 'authority_mark', title: '权限标识', minWidth: 120},
                {title: '默认展开', width: 100, align: "center", templet: function (d) {
                    if (d.btn) return
                    return '<input type="checkbox" value="'+d.id+'" lay-skin="switch" lay-text="true|false" lay-filter="open-switch" '+(d.open?"checked":"")+'>'
                }},
                {
                    title: "关联菜单", unresize: true, width: 140, align: "center", templet: function (d) {
                        if (d.menu_id && d.btn===false){
                            return '<span class="layui-badge" style="background-color: #673ab7">'+d.menu_name+'</span>'
                        }else if(d.btn === true){
                            return '<span class="layui-badge layui-bg-cyan">按钮</span>'
                        }
                    }
                },
                {field: 'sort', title: '排序', width: 100, align: "center"},
                {field: "created_time", width: 180, sort: true, title: '创建时间',},
                {field: "update_time", width: 180, sort: true, title: '修改时间',},
                {templet: '#auth-state', width: 260, unresize: false, title: '操作', fixed: 'right'},
            ]],
            //height: "full-40",
            reqData: function(data, callback) {
                $.ajax({
                    url: "/authority/selectAll",
                    success:function(res){
                        callback(res.data);
                    },
                })
            },
            done: function(){
                element.render('nav');
                $(".ew-tree-table-head .layui-table").width($(".ew-tree-table-box .layui-table").width())
            }
        });

        window.onresize = function(){
            $(".ew-tree-table-head .layui-table").width($(".ew-tree-table-box .layui-table").width())
        }

        // 头部工具栏点击事件
        treeTable.on('toolbar(menuTreeTb)', function (obj) {
            switch (obj.event) {
                case 'newModel':
                    flag = true
                    setAuthority.setValue([])
                    form.val("form-obj",{
                        pid: "",
                        id: "",
                        sort: "",
                        btn: false,
                        authorityName: "",
                        authorityMark: ""
                    });
                    layer.open({
                        type: 1,
                        area: ["100%", '100%'],
                        maxmin: true,
                        content: $(".add-menu-form"),
                        title: "新增",
                        scrollbar: false
                    })
                    break;
                case "refresh":
                    treeTb.reload()
            }
        });

        //监听工具条
        treeTable.on('tool(menuTreeTb)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            $('input[name="authorityMark"]').removeAttr("disabled")
            $('input[name="btn"]').removeAttr("disabled")
            if (layEvent === 'del') {
                layer.confirm('确定删除 <span style="color: red; font-weight: 800">'+data.authority_name+'</span> 么？', {icon: 3, title:'提示'}, function(index){
                    layer.close(index);
                    layer.load()
                    $.ajax({
                        url: '/authority/deleteById',
                        data: {id: data.id},
                        success: function(result) {
                            if (result.code == 200) {
                                treeTb.reload();
                                getTree()
                                layer.closeAll('loading')
                                layer.msg("删除成功")
                            } else {
                                layer.closeAll('loading')
                                layer.msg("删除失败")
                            };
                        },
                        error: function() {
                            layer.closeAll('loading')
                            layer.msg("服务错误")
                        }
                    });
                });
            } else if (layEvent === 'edit') {
                flag = false
                $('input[name="authorityMark"]').attr("disabled", "")
                if (data.menu_id)
                    $('input[name="btn"]').attr("disabled", "")
                setAuthority.setValue([data.pid]);
                form.val("form-obj", {
                    pid: data.pid,
                    id: data.id,
                    sort: data.sort,
                    btn: data.btn,
                    authorityMark: data.authority_mark,
                    authorityName: data.authority_name
                })

                layer.open({
                    type: 1,
                    area: ["100%", '100%'],
                    maxmin: true,
                    content: $(".add-menu-form"),
                    title: "编辑",
                    scrollbar: false
                })
                // layer.msg('修改' + data.mId);
            } else if(layEvent === 'add'){
                flag = true
                setAuthority.setValue([data.id])
                form.val("form-obj",{
                    pid: data.id,
                    id: "",
                    sort: "",
                    btn: false,
                    authorityMark: data.authority_mark+".",
                    authorityName: ""
                });
                layer.open({
                    type: 1,
                    area: ["100%", '100%'],
                    maxmin: true,
                    content: $(".add-menu-form"),
                    title: "新增",
                    scrollbar: false
                })
            }else if(layEvent === "associate"){
                layer.load()
                $.ajax({
                    url: "/authority/checkMenu",
                    data: {pId: data.pid},
                    success: function (res) {
                        if(res.code==200){
                            $.ajax({
                                url: "/menu/selectMenuTreeByPid",
                                data: {pId: res.data, id: data.menu_id},
                                success: function (r) {
                                    setTree.update({
                                        data: r.data
                                    })
                                    window.aId = data.id
                                    setTree.changeExpandedKeys(true)
                                    setTimeout(function () {
                                        setTree.setValue([data.menu_id||""])
                                        layer.closeAll()
                                        layer.open({
                                            type: 1,
                                            //area: ["100%", '100%'],
                                            //maxmin: true,
                                            content: $(".menu-box"),
                                            title: false,
                                            scrollbar: false
                                        })
                                    },500)
                                },
                                error(){
                                    layer.closeAll()
                                }
                            })
                        }else {
                            layer.closeAll()
                            layer.msg(res.msg, {
                                icon: 0,
                                shade: 0.1,
                                time: 2000
                            });
                        }
                    }
                })
            }
        });

        // 监听展开开关
        form.on('switch(open-switch)', function(obj){
            layer.load()
            $.ajax({
                url: "/authority/openStatus",
                data: {id: this.value, open: obj.elem.checked},
                success(res){
                    layer.closeAll("loading")
                    if(res.code === 200){
                        obj.elem.checked?layer.tips("默认展开", obj.othis):layer.tips("默认折叠", obj.othis)
                    }else {
                        layer.tips("操作无效", obj.othis)
                    }
                },
                error(err){
                    layer.closeAll("loading")
                    layer.tips("操作无效", obj.othis)
                    console.log(res)
                }
            })
        });

        form.on('submit(add)', function(data){
            if (!data.field.btn){
                data.field.btn = false
            }else if (data.field.btn && data.field.btn==="on") {
                data.field.btn = true
            }
            layer.load()
            $.ajax({
                url: data.field.id!==null&&data.field.id!==""?"/authority/update":"/authority/save",
                type: "POST",
                data: data.field,
                success: function (res) {
                    if (res.code == 200) {
                        treeTb.refresh();
                        getTree()
                        layer.closeAll()
                        layer.msg("操作成功")
                    } else {
                        layer.closeAll('loading')
                        layer.msg(res.msg)
                    };
                },
                error: function() {
                    layer.closeAll('loading')
                    layer.msg("服务出错")
                }
            })

            return false;
        });

        //监听指定开关
        form.on('switch(switchIsPage)', function(data){
            if(this.checked){
                $("#showUrl").removeClass("layui-hide")
            }else{
                $("#showUrl").addClass("layui-hide")
            }
        });


        var setAuthority = xmSelect.render({
            el: '#setAuthority',
            autoRow: true,
            name: "authorityList",
            tips: '请选择上级节点',
            layVerify: 'required',
            searchTips: '搜索节点',
            filterable: true,
            direction: 'down',
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 35,
                expandedKeys: ["0"],
                //是否严格遵守父子模式
                strict: false,
                //是否开启极简模式
                simple: false,
                clickCheck: true,
                clickExpand: false
            },
            prop: {
                name: 'title',
                value: 'id'
            },
            radio: true,
            model: {
                type: 'absolute',
            },
            on: function(data){
                if(data.arr.length>0){
                    if (flag){
                        form.val("form-obj",{
                            pid: data.arr[0].id,
                            authorityMark: data.arr[0].mark!=""?data.arr[0].mark+".":data.arr[0].mark
                        });
                    }else {
                        form.val("form-obj",{
                            pid: data.arr[0].id
                        });
                    }
                }
            },
            theme: {
                color: '#1c86bb',
            },
            toolbar: {
                show: true,
                list: ['ALL', 'REVERSE', 'CLEAR']
            },
            height: '420px',
        })

        var setTree = xmSelect.render({
            el: '#setTree',
            autoRow: true,
            filterable: true,
            paging: true,
            radio: true,
            searchTips: '搜索菜单',
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 35,
                expandedKeys: true,
                strict: false,
                //点击节点是否展开
                clickExpand: false,
                //点击节点是否选中
                clickCheck: true,
            },
            prop: {
                name: 'title',
                //value: 'id'
            },
            model: {
                type: 'relative',
            },
            on: function(data) {
                if(data.arr.length > 0){
                    layer.load()
                    $.ajax({
                        type: "POST",
                        url: "/authority/associate",
                        data: {aId: aId, mId: data.arr[0].value},
                        success:function(res){
                            layer.closeAll()
                            if(res.code===200){
                                treeTb.reload()
                                layer.msg("关联成功");
                            }else{
                                layer.msg("关联失败");
                            }
                        },
                        error() {
                            layer.closeAll()
                            layer.msg("请求失败");
                        }
                    })
                }else {
                    // 取消关联
                    layer.load()
                    $.ajax({
                        type: "POST",
                        url: "/authority/disAssociate",
                        data: {aId: aId},
                        success:function(res){
                            layer.closeAll()
                            if(res.code===200){
                                treeTb.reload()
                                layer.msg("操作成功");
                            }else{
                                layer.msg("操作失败");
                            }
                        },
                        error() {
                            layer.closeAll()
                            layer.msg("请求失败");
                        }
                    })
                }
            },
            theme: {
                color: '#00aa7f',
            },
            height: '480px',
        })

        getTree()

        function getTree() {
            $.ajax({
                url: '/authority/selectTree',
                success: function(result) {
                    setAuthority.update({
                        data: result.data
                    })
                    setAuthority.changeExpandedKeys(true)
                },
                error: function() {
                    layer.msg("服务错误")
                }
            });
        }

    })
</script>
</body>
</html>